<?php

namespace app\api\controller;

use app\admin\app\model\MaterialSubtitle;
use app\admin\app\model\Qiniu;
use app\admin\app\model\Video;
use support\Request;

class CapcutController
{
    public function getTask(Request $request)
    {
        $subtitle = MaterialSubtitle::where(['status' => 0])->first();
        if (empty($subtitle)) {
            return json(['code' => 0, 'msg' => '暂无任务']);
        }
        $subtitle->status = 1;
        $subtitle->save();
        return json(['code' => 1, 'data' => $subtitle->toArray()]);
    }

    public function complete(Request $request)
    {
        $subtitle = MaterialSubtitle::find($request->input('id'));
        if (empty($subtitle) || $subtitle->status !== 1) {
            return json(['code' => 0, 'msg' => '任务不存在']);
        }
        $file = current($request->file());
        $qiniu = new Qiniu();
        list($data, $err) = $qiniu->upload($file);
        if ($err !== null) {
            return json(['code' => 0, 'msg' => '保存文件失败' . $err]);
        }
        $video = Video::create([
            'admin_id' => $subtitle->admin_id,
            'category_id' => $subtitle->category_id,
            'filename' => basename($data['key']),
            'path' => $data['key'],
            'merge_id' => $subtitle->id,
        ]);
        if ($video->id) {
            $subtitle->video_id = $video->id;
            $subtitle->status = 2;
            $subtitle->save();
        }
        return json(['code' => 1, 'msg' => 'ok']);
    }
}
